import psycopg2
from psycopg2 import OperationalError

class ConnectionManager:
    """Just do one thing: keep the connection and answer 'Can I connect' and 'Who is the current library?'"""
    def __init__(self):
        self.conn = None
        self.current_db = None

    def login(self, user: str, pwd: str):
        """Successful return (conn, dbname), failure throws an exception"""
        for db in ("postgres", "template1"):
            try:
                conn = psycopg2.connect(host="localhost", port=5432,
                                      database=db, user=user, password=pwd)
                break
            except OperationalError:
                continue
        else:
            raise OperationalError("Unable to connect to the server")

        with conn.cursor() as cur:
            cur.execute("SELECT datname FROM pg_database "
                      "WHERE datistemplate=false ORDER BY datname LIMIT 1")
            row = cur.fetchone()
            if not row:
                raise RuntimeError("No service library")
            first_db = row[0]
        conn.close()

        # Officially connected to the target library
        self.conn = psycopg2.connect(host="localhost", port=5432,
                                   database=first_db, user=user, password=pwd)
        self.current_db = first_db
        return self.conn, first_db

    def close(self):
        if self.conn:
            self.conn.close()
            self.conn = None